package com.dzl.goods.service.impl;

import com.dzl.base.service.BaseServiceImpl;
import com.dzl.config.exception.CommonException;
import com.dzl.goods.dao.WelfareGoodsClassifyMapper;
import com.dzl.goods.pojo.WelfareGoodsClassify;
import com.dzl.goods.pojo.query.WelfareGoodsClassifyQuery;
import com.dzl.goods.pojo.vo.WelfareGoodsClassifyVo;
import com.dzl.goods.service.WelfareGoodsClassifyService;
import com.dzl.util.EmptyUtils;
import com.dzl.util.ImageUtils;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品分类表(WelfareGoodsClassify)表服务实现类
 * @author ChenLong
 * @since 2021-05-18 10:42:58
 */
@Slf4j
@Service("welfareGoodsClassifyService")
public class WelfareGoodsClassifyServiceImpl extends BaseServiceImpl<WelfareGoodsClassify> implements WelfareGoodsClassifyService {
    @Autowired
    private WelfareGoodsClassifyMapper mapper;

    @Override
    public List<WelfareGoodsClassifyVo> getGoodsClassify(Integer enterpriseId) {
        WelfareGoodsClassify welfareGoodsClassify = new WelfareGoodsClassify();
        welfareGoodsClassify.setStatus(1);
        welfareGoodsClassify.setEnterpriseId(enterpriseId);
        List<WelfareGoodsClassifyVo> welfareGoodsClassifyVoList = mapper.queryAll(welfareGoodsClassify);
        if (EmptyUtils.isNotEmpty(welfareGoodsClassifyVoList)) {
            welfareGoodsClassifyVoList.forEach(vo -> {
                if (EmptyUtils.isNotEmpty(vo.getImg())) {
                    vo.setImg(ImageUtils.setImageSrc(vo.getImg()));
                }
                if (EmptyUtils.isNotEmpty(vo.getParentId()) && vo.getParentId() != 0) {
                    WelfareGoodsClassify parent = mapper.selectByPrimaryKey(vo.getParentId());
                    vo.setParentName(parent.getName());
                }
            });
            return findTree(welfareGoodsClassifyVoList);
        } else {
            return welfareGoodsClassifyVoList;
        }
    }

    @Override
    public List<WelfareGoodsClassifyVo> getGoodsClassifyWithOutEmptySub(Integer enterpriseId) {
        WelfareGoodsClassify welfareGoodsClassify = new WelfareGoodsClassify();
        welfareGoodsClassify.setStatus(1);
        welfareGoodsClassify.setIsShow(1);
        //先查所有3级
        welfareGoodsClassify.setLevel(3);
        welfareGoodsClassify.setEnterpriseId(enterpriseId);
        List<WelfareGoodsClassifyVo> childList = mapper.queryAll(welfareGoodsClassify);
        if (CollectionUtils.isEmpty(childList)) {
            return new ArrayList<>();
        }
        List<WelfareGoodsClassifyVo> welfareGoodsClassifyVoList = getGoodsClassifyByThirdLevel(childList);
        if (EmptyUtils.isNotEmpty(welfareGoodsClassifyVoList) && welfareGoodsClassifyVoList.size() > 0) {
            // 添加全部分类
            return addAllMenuForGoodsClassify(welfareGoodsClassifyVoList);
        }else{
            return new ArrayList<>();
        }
    }

    /**
     * 添加全部分类
     * @author ChenLong
     * @date 2021-07-31 15:55:34
     * @param welfareGoodsClassifyVoList 分类列表
     * @return void
     **/
    private List<WelfareGoodsClassifyVo> addAllMenuForGoodsClassify(List<WelfareGoodsClassifyVo> welfareGoodsClassifyVoList){
        Map<Integer, List<WelfareGoodsClassifyVo>> goodsClassifyAllMap = new HashMap<>();
        for (WelfareGoodsClassifyVo welfareGoodsClassifyVo : welfareGoodsClassifyVoList) {
            if (EmptyUtils.isNotEmpty(welfareGoodsClassifyVo.getLevel()) && welfareGoodsClassifyVo.getLevel() == 1) {
                List<WelfareGoodsClassifyVo> welfareGoodsClassifyVoListTemp = new ArrayList<>(welfareGoodsClassifyVo.getChildren());
                if (goodsClassifyAllMap.containsKey(-1)) {
                    goodsClassifyAllMap.get(-1).addAll(welfareGoodsClassifyVoListTemp);
                } else {
                    goodsClassifyAllMap.put(-1, welfareGoodsClassifyVoListTemp);
                }
            }
        }
        WelfareGoodsClassifyVo welfareGoodsClassifyVoAll = new WelfareGoodsClassifyVo();
        welfareGoodsClassifyVoAll.setId(0);
        welfareGoodsClassifyVoAll.setName("全部分类");
        welfareGoodsClassifyVoAll.setParentId(0);
        welfareGoodsClassifyVoAll.setSort(0);
        welfareGoodsClassifyVoAll.setChildren(goodsClassifyAllMap.get(-1));
        welfareGoodsClassifyVoAll.setCreateTime(new Date());
        welfareGoodsClassifyVoAll.setUpdateTime(new Date());
        welfareGoodsClassifyVoList.add(welfareGoodsClassifyVoAll);
        // 根据sort排序
        return welfareGoodsClassifyVoList.stream().sorted(Comparator.comparing(WelfareGoodsClassifyVo::getSort)).collect(Collectors.toList());
    }

    /**
     * 根据三级子节点获取一二级父节点列表
     * @author ChenLong
     * @date 2021-07-31 15:19:32
     * @param childList 三级分类列表
     * @return java.util.List<com.dzl.goods.pojo.vo.WelfareGoodsClassifyVo>
     **/
    private List<WelfareGoodsClassifyVo> getGoodsClassifyByThirdLevel(List<WelfareGoodsClassifyVo> childList) {
        //再查所有3级的父级
        StringBuffer parentIds = new StringBuffer();
        childList.forEach(child -> {
            parentIds.append(child.getParentId()).append(",");
        });
        if (parentIds.length() > 0 && parentIds.substring(parentIds.length() - 1).equals(",")) {
            parentIds.deleteCharAt(parentIds.length() - 1);
        }
        List<WelfareGoodsClassifyVo> parentList = mapper.selectParentByIds(parentIds.toString());
        //再查所有3级的父级的父级
        StringBuffer grandpaIds = new StringBuffer();
        parentList.forEach(parent -> {
            grandpaIds.append(parent.getParentId()).append(",");
        });
        if (grandpaIds.length() > 0 && grandpaIds.substring(grandpaIds.length() - 1).equals(",")) {
            grandpaIds.deleteCharAt(grandpaIds.length() - 1);
        }
        List<WelfareGoodsClassifyVo> grandpaList = mapper.selectParentByIds(grandpaIds.toString());
        //组装所有等级的分类
        List<WelfareGoodsClassifyVo> list = new ArrayList<>();
        list.addAll(childList);
        list.addAll(parentList);
        list.addAll(grandpaList);
        if (EmptyUtils.isNotEmpty(list)) {
            list.forEach(vo -> {
                if (EmptyUtils.isNotEmpty(vo.getImg())) {
                    vo.setImg(ImageUtils.setImageSrc(vo.getImg()));
                }
            });
        }
        return findTree(list);
    }

    @Override
    public List<WelfareGoodsClassifyVo> getGoodsClassifyByThirdIdList(List<Integer> list) {
        List<WelfareGoodsClassifyVo> thirdIdList = mapper.getGoodsClassifyByThirdIdList(list);

        if (CollectionUtils.isEmpty(thirdIdList)) {
            return new ArrayList<>();
        }
        List<WelfareGoodsClassifyVo> welfareGoodsClassifyVoList =getGoodsClassifyByThirdLevel(thirdIdList);
        if (EmptyUtils.isNotEmpty(welfareGoodsClassifyVoList) && welfareGoodsClassifyVoList.size() > 0) {
            // 添加全部分类
            return addAllMenuForGoodsClassify(welfareGoodsClassifyVoList);
        }else{
            return new ArrayList<>();
        }
    }

    @Override
    public List<WelfareGoodsClassifyVo> getGoodsClassifyPage(WelfareGoodsClassifyQuery query) {
        try {
            PageHelper.startPage(query);
            List<WelfareGoodsClassifyVo> welfareGoodsClassifyVoList = mapper.selectGoodsClassifyPage(query);
            welfareGoodsClassifyVoList.forEach(vo -> {
                if (EmptyUtils.isNotEmpty(vo.getImg())) {
                    vo.setImg(ImageUtils.setImageSrc(vo.getImg()));
                }
                if (EmptyUtils.isNotEmpty(vo.getParentId()) && vo.getParentId() != 0) {
                    WelfareGoodsClassify parent = mapper.selectByPrimaryKey(vo.getParentId());
                    vo.setParentName(parent.getName());
                }
                int countGrandson = 0;
                //如果有孙子分类，子分类数量要加上孙子分类数量
                if (EmptyUtils.isNotEmpty(vo.getChildren())) {
                    countGrandson += vo.getChildren().size();
                }
                vo.setCountChild(vo.getCountChild() + countGrandson);
            });
            welfareGoodsClassifyVoList.sort(sort());
            return welfareGoodsClassifyVoList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException("测试数据错误！");
        }
    }

    @Override
    public Integer deleteGoodsClassify(Integer id, Integer loginId) {
        WelfareGoodsClassify entity = mapper.selectByPrimaryKey(id);
        Integer countGoods = mapper.selectCountGoodsById(id, entity.getLevel());
        if (countGoods > 0) {
            throw new CommonException("该分类已关联商品，无法删除！");
        }
        Boolean isBindGoods = getAllChildrenIsBindGoods(id);
        if (isBindGoods) {
            throw new CommonException("该分类有子分类已关联商品，无法删除！");
        }
        entity.setUpdateTime(new Date());
        entity.setUpdater(loginId);
        entity.setStatus(0);
        return mapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public Boolean getAllChildrenIsBindGoods(Integer id) {
        List<WelfareGoodsClassify> list = mapper.selectAllChildren(id);
        if (CollectionUtils.isEmpty(list)) {
            return false;
        }
        for (WelfareGoodsClassify classify : list) {
            Integer countGoods = mapper.selectCountGoodsById(classify.getId(), classify.getLevel());
            if (countGoods > 0) {
                return true;
            }
            getAllChildrenIsBindGoods(classify.getId());
        }
        return false;
    }

    @Override
    public List<Map<String, Object>> getGoodsClassifiesForSelect(Integer enterpriseId) {
        WelfareGoodsClassify welfareGoodsClassify = new WelfareGoodsClassify();
        welfareGoodsClassify.setStatus(1);
        //先查所有3级
        welfareGoodsClassify.setLevel(3);
//        welfareGoodsClassify.setIsShow(1);
        welfareGoodsClassify.setEnterpriseId(enterpriseId);
        List<WelfareGoodsClassifyVo> childList = mapper.queryAll(welfareGoodsClassify);
        if (CollectionUtils.isEmpty(childList)) {
            return new ArrayList<>();
        }
        //再查所有3级的父级
        StringBuffer parentIds = new StringBuffer();
        childList.forEach(child -> {
            parentIds.append(child.getParentId()).append(",");
        });
        if (parentIds.length() > 0 && parentIds.substring(parentIds.length() - 1).equals(",")) {
            parentIds.deleteCharAt(parentIds.length() - 1);
        }
        List<WelfareGoodsClassifyVo> parentList = mapper.selectParentByIds(parentIds.toString());
        //再查所有3级的父级的父级
        StringBuffer grandpaIds = new StringBuffer();
        parentList.forEach(parent -> {
            grandpaIds.append(parent.getParentId()).append(",");
        });
        if (grandpaIds.length() > 0 && grandpaIds.substring(grandpaIds.length() - 1).equals(",")) {
            grandpaIds.deleteCharAt(grandpaIds.length() - 1);
        }
        List<WelfareGoodsClassifyVo> grandpaList = mapper.selectParentByIds(grandpaIds.toString());
        //组装所有等级的分类
        List<WelfareGoodsClassifyVo> list = new ArrayList<>();
        list.addAll(childList);
        list.addAll(parentList);
        list.addAll(grandpaList);
        List<WelfareGoodsClassifyVo> listVo = findTree(list);
        return getChildrenMapList(listVo);
    }

    /**
     * 递归商品分类树，更改属性名和属性值
     * @param list 商品分类树列表
     * @return java.util.List
     * @date 2021/6/3 11:57
     * @author caobucao
     */
    public List<Map<String, Object>> getChildrenMapList(List<WelfareGoodsClassifyVo> list) {
        List<Map<String, Object>> listMap = new ArrayList<>();
        list.forEach(vo -> {
            Map<String, Object> map = new HashMap<>();
            map.put("label", vo.getName());
            map.put("value", vo.getId());
            if (EmptyUtils.isNotEmpty(vo.getChildren())) {
                List<Map<String, Object>> child = getChildrenMapList(vo.getChildren());
                map.put("children", child);
            }
            listMap.add(map);
        });
        return listMap;
    }

    /**
     * 排序,根据sort排序
     * @param
     * @return java.util.Comparator<com.dzl.goods.entity.WelfareGoodsClassify>
     * @author ChenLong
     * @since 2021-05-18 16:33:48
     **/
    public Comparator<WelfareGoodsClassifyVo> sort() {
        Comparator<WelfareGoodsClassifyVo> comparator = new Comparator<WelfareGoodsClassifyVo>() {
            @Override
            public int compare(WelfareGoodsClassifyVo o1, WelfareGoodsClassifyVo o2) {
                if (!o1.getSort().equals(o2.getSort())) {
                    return o1.getSort() - o2.getSort();
                }
                return 0;
            }
        };
        return comparator;
    }

    /**
     * 获取节点树
     * @param allWelfareGoodsClassify 商品分类列表
     * @return java.util.List<com.dzl.goods.entity.WelfareGoodsClassify>
     * @author ChenLong
     * @since 2021-05-18 16:34:07
     **/
    public List<WelfareGoodsClassifyVo> findTree(List<WelfareGoodsClassifyVo> allWelfareGoodsClassify) {
        try {
            // 根节点
            List<WelfareGoodsClassifyVo> rootWelfareGoodsClassify = new ArrayList<>();
            for (WelfareGoodsClassifyVo nav : allWelfareGoodsClassify) {
                //父节点是0的，为根节点
                if (nav.getParentId() == 0) {
                    rootWelfareGoodsClassify.add(nav);
                }
            }
            // 根据WelfareGoodsClassify类的order排序
            Collections.sort(rootWelfareGoodsClassify, sort());
            //为根节点设置子节点，getClild是递归调用的
            for (WelfareGoodsClassifyVo nav : rootWelfareGoodsClassify) {
                // 获取根节点下的所有子节点 使用getChild方法
                List<WelfareGoodsClassifyVo> childList = getChild(nav.getId(), allWelfareGoodsClassify);
                nav.setChildren(childList);//给根节点设置子节点
            }
            return rootWelfareGoodsClassify;
        } catch (Exception e) {
            log.error("findTree e: " + e.getMessage(), e);
            return null;
        }
    }

    /**
     * 获取子节点
     * @param id                      行id
     * @param allWelfareGoodsClassify 商品分类列表
     * @return java.util.List<com.dzl.goods.entity.WelfareGoodsClassify>
     * @author ChenLong
     * @since 2021-05-18 16:33:03
     **/
    public List<WelfareGoodsClassifyVo> getChild(Integer id, List<WelfareGoodsClassifyVo> allWelfareGoodsClassify) {
        //子菜单
        List<WelfareGoodsClassifyVo> childList = new ArrayList<>();
        for (WelfareGoodsClassifyVo nav : allWelfareGoodsClassify) {
            // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
            // 相等说明：为该根节点的子节点。
            if (nav.getParentId().equals(id)) {
                childList.add(nav);
            }
        }
        // 递归
        for (WelfareGoodsClassifyVo nav : childList) {
            nav.setChildren(getChild(nav.getId(), allWelfareGoodsClassify));
        }
        Collections.sort(childList, sort()); //排序
        // 如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }

    @Override
    public List<Map<String, Object>> getCategoryListByMiddleground(Integer parentId) {
        return mapper.getCategoryListByMiddleground(parentId);
    }
}
